#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void writer(int wfd)
{
    char outbuffer[128] = {0};
    int cnt = 1;
    while (1)
    {
        // sleep(10);  // 管道为空 读端阻塞
        // sprintf(outbuffer, "message:%s, count:%d\n", "hello father, I am child", cnt);
        //  写入数据
        char ch = 'A';
        write(wfd, &ch, 1); // 读端关闭时，再写入OS就会将这个进程发送13号信号
        printf("cnt:%d\n", cnt);
        cnt++;
        // if (cnt == 10)
        // {
        //     break;
        // }
        sleep(1);
    }
    close(wfd); // 写端关闭
}

void reader(int rfd)
{
    char buffer[1024] = {0};
    int cnt = 1;
    while (1)
    {
        // 读取数据
        sleep(1); // 管道为满，写端阻塞

        int n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            printf("father recv a message:%s\n", buffer);
        }
        else if (n == 0)
        {
            // 写端关闭 read 函数返回0，类似读取到文件末尾
            printf("read pipe done, read file done!\n");
            break;
        }
        else
            break;
        cnt++;
        if (cnt == 10)
        {
            printf("read endpoint exit!\n");
            break;
        }
    }
    close(rfd);
}
int main()
{
    int pipefd[2];
    // 1.申请管道
    int n = pipe(pipefd);
    // 2.fork子进程
    ssize_t id = fork();
    if (id == 0)
    {
        // child:w
        // 3.关闭读管道
        close(pipefd[0]);
        writer(pipefd[1]);
        exit(0);
    }
    // parent:r
    close(pipefd[1]);
    reader(pipefd[0]);
    int status;
    pid_t rid = waitpid(id, &status, 0);
    printf("exit code:%d, exit signal:%d\n", WEXITSTATUS(status), status & 0x7f);
    return 0;
}